const MenuModal = require("@/model/Menu");
const { Op } = require("sequelize");

const menu = {
  async GetMenusByUserInfoId(userInfoId) {
    try {
      const [rows, fields] = await global.mysqlPool.execute(
        `
      SELECT DISTINCT m.id, name, path, component, icon, is_hidden, keep_alive, redirect, parent_id, order_num
      FROM user_role ur
      JOIN role_menu rm ON ur.role_id = rm.role_id
      JOIN menu m ON rm.menu_id = m.id
      where user_id = ?
      `,
        [userInfoId]
      );

      return rows;
    } catch (error) {
      console.log("查询用户对应菜单失败", error);
    }
  },
  async GetMenus(query) {
    let list = [];

    if (query?.keyword) {
      list = await MenuModal.Menu.findAll({
        where: {
          name: {
            [Op.like]: `%${query.keyword}%`,
          },
        },
      });
    } else {
      list = await MenuModal.Menu.findAll();
    }
    list = list.map((item) => {
      return item.dataValues;
    });
    return list;
  },
};

module.exports = menu;
